<template>
  <div class="about">
    <div ref="chart" style="width: 800px;height:500px;margin: 50px 0 0 50px;"></div>
  </div>
</template>
<script>
// 导入图表
import echarts from 'echarts'
// 导入中国地图
import 'echarts/map/js/china'
import { reactive,ref,onMounted } from 'vue'
import { getUserList} from '../../api/userApi.ts'

export default {
  // 启动函数
  setup(){
    const state = reactive({
      chart:ref()
    })

    var userData = ref([])

    const init = () => {
      if(state.chart){
        // 图表的初始化
        let mycat = echarts.init(state.chart)
        const option = {
          title:{
            text:'用户分布图',
            x:'center',
            textStyle: {
              color:'#9c0505'
            }
          },
          // 数据和类型
          series: [{
            type:'map',
            map:'china',
            label:{
              show: true,
              color:'red',
              fontSize:10
            },
            // 地图大小倍数
            zoom:1.2,
            data:userData.value
          }],
          visualMap:{
            min: 0,
            max: 50,
            text: ['High', 'Low'],
            realtime: false,
            calculable: true,
            inRange: {
              color: ['lightskyblue', 'yellow', 'orangered']
            }
          }
        }
        // 指定数据项和数据显示
        mycat.setOption(option);
      }
    }

    const fetchUserList = async () => {
        try {
          const res = await getUserList();
          const provinceCount = {};

          for (let i = 0; i < res.length; i++) {
            if (res[i].role != "0") {
              const str = res[i].companyName;
              const match = str.match(/(.*)总公司/);

              if (match) {
                const province = match[1];
                console.log(province);
                if (provinceCount[province]) {
                  provinceCount[province]++;
                } else {
                  provinceCount[province] = 1;
                }
              }
            }
          }

          userData.value = []
          for (var i in provinceCount) {
            userData.value.push({name: i, value: provinceCount[i]})
          }
          
          init();
        } catch (error) {
          console.log("获取用户列表失败");
        }
      };

    onMounted(() => {
      fetchUserList();
    })

    return state
  }
}
</script>
